<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>svg</title>
</head>
<body>
<p>p1</p>
<p>p2</p>
<p>p3</p>



<button type="button" onclick="mySort()">排序</button>

<button type="button" onclick="setdata(1)">增加</button>
<button type="button" onclick="setdata(-1)">减少</button>


<script src="https://cdn.jsdelivr.net/npm/d3@5.7.0/dist/d3.min.js"></script>
<script type="text/javascript">
    var dataset = [55, 36, 84, 96, 115, 336, 12];
    var width = 400, height = 400;
    var padding = {top: 20, right: 20, bottom: 20, left: 20};
    var rectStep = 35;
    var rectWidth = 30;
    var svg = d3.select("body")
        .append("svg").attr("width", width).attr("height", height);
    var rect = svg.selectAll("rect")
        .data(dataset)
        .enter()
        .append("rect")
        .attr("fill", "steelblue")
        .attr("x", function (d, i) {
            return padding.left + rectStep * i;
        })
        .attr("y", function (d, i) {
            return height - padding.bottom - d;
        })
        .attr("width", rectWidth)
        .attr("height", function (d, i) {
            return d;
        });
    var text = svg.selectAll("text")
        .data(dataset)
        .enter()
        .append("text")
        .attr("fill", "white")
        .attr("font-size", "14px")
        .attr("text-anchor", "middle")
        .attr("x", function (d, i) {
            return padding.left + rectStep * i;
        })
        .attr("y", function (d, i) {
            return height - padding.bottom - d;
        })
        .attr("dx", rectStep / 2)
        .attr("dy", "1em")
        .text(function (d, i) {
            return d;
        });

    function draw() {
        var update = svg.selectAll("rect").data(dataset);
        var enter = update.enter();
        var exit = update.exit();
        update.attr("fill", "steelblue")
            .attr("x", function (d, i) {
                return padding.left + rectStep * i;
            })
            .attr("y", function (d, i) {
                return height - padding.bottom - d;
            })
            .attr("width", rectWidth)
            .attr("height", function (d, i) {
                return d;
            });
        enter.append("rect")
            .attr("fill", "steelblue")
            .attr("x", function (d, i) {
                return padding.left + rectStep * i;
            })
            .attr("y", function (d, i) {
                return height - padding.bottom - d;
            })
            .attr("width", rectWidth)
            .attr("height", function (d, i) {
                return d;
            });
        exit.remove();
    }
    
    function mySort() {
        dataset.sort(d3.ascending);
        draw();
    }
    function setdata(d) {
        if(d>0){
            dataset.push(Math.floor(Math.random()*100));
            draw();
        }else{
            dataset.pop();
            draw();
        }

    }

</script>
</body>
</html>